<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 6.3.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/myblog/images/apple-touch-icon.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/myblog/images/favicon-32x32.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/myblog/images/favicon-16x16.png">
  <link rel="mask-icon" href="/myblog/images/logo.svg" color="#222">

<link rel="stylesheet" href="/myblog/css/main.css">

<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Monda:300,300italic,400,400italic,700,700italic%7CRoboto+Slab:300,300italic,400,400italic,700,700italic%7CNoto+Serif+SC:300,300italic,400,400italic,700,700italic%7CAmita:300,300italic,400,400italic,700,700italic%7CMontserrat:300,300italic,400,400italic,700,700italic%7CPT+Mono:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha256-AbA177XfpSnFEvgpYu1jMygiLabzPCJCRIBtR5jGc0k=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"wang-chen1119.gitee.io","root":"/myblog/","images":"/myblog/images","scheme":"Pisces","darkmode":false,"version":"8.13.1","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":{"enable":false,"style":null},"bookmark":{"enable":true,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"}}</script><script src="/myblog/js/config.js"></script>

    <meta name="description" content="java 8 新特性1. Lambda表达式:book:  Lambda是一个匿名函数，让代码像数据一样进行传递，让代码更加简洁与灵活。 举例 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748public class LambdaTest &amp;#123;    @Test">
<meta property="og:type" content="blog">
<meta property="og:title" content="java8新特性">
<meta property="og:url" content="http://wang-chen1119.gitee.io/myblog/2022/10/28/java%208%20%E6%96%B0%E7%89%B9%E6%80%A7/index.html">
<meta property="og:site_name" content="Yorn&#39;s Notes">
<meta property="og:description" content="java 8 新特性1. Lambda表达式:book:  Lambda是一个匿名函数，让代码像数据一样进行传递，让代码更加简洁与灵活。 举例 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748public class LambdaTest &amp;#123;    @Test">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://wang-chen1119.gitee.io/myblog/java%208%20%E6%96%B0%E7%89%B9%E6%80%A7.assets/copycode.gif">
<meta property="og:image" content="http://wang-chen1119.gitee.io/myblog/java%208%20%E6%96%B0%E7%89%B9%E6%80%A7.assets/copycode.gif">
<meta property="og:image" content="http://wang-chen1119.gitee.io/myblog/java%208%20%E6%96%B0%E7%89%B9%E6%80%A7.assets/copycode.gif">
<meta property="og:image" content="http://wang-chen1119.gitee.io/myblog/java%208%20%E6%96%B0%E7%89%B9%E6%80%A7.assets/copycode.gif">
<meta property="og:image" content="http://wang-chen1119.gitee.io/myblog/java%208%20%E6%96%B0%E7%89%B9%E6%80%A7.assets/copycode.gif">
<meta property="og:image" content="http://wang-chen1119.gitee.io/myblog/java%208%20%E6%96%B0%E7%89%B9%E6%80%A7.assets/copycode.gif">
<meta property="og:image" content="http://wang-chen1119.gitee.io/myblog/java%208%20%E6%96%B0%E7%89%B9%E6%80%A7.assets/copycode.gif">
<meta property="og:image" content="http://wang-chen1119.gitee.io/myblog/java%208%20%E6%96%B0%E7%89%B9%E6%80%A7.assets/copycode.gif">
<meta property="article:published_time" content="2022-10-28T08:51:27.213Z">
<meta property="article:modified_time" content="2022-10-28T08:52:02.513Z">
<meta property="article:author" content="yorn">
<meta property="article:tag" content="java基础">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://wang-chen1119.gitee.io/myblog/java%208%20%E6%96%B0%E7%89%B9%E6%80%A7.assets/copycode.gif">


<link rel="canonical" href="http://wang-chen1119.gitee.io/myblog/2022/10/28/java%208%20%E6%96%B0%E7%89%B9%E6%80%A7/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"http://wang-chen1119.gitee.io/myblog/2022/10/28/java%208%20%E6%96%B0%E7%89%B9%E6%80%A7/","path":"2022/10/28/java 8 新特性/","title":"java8新特性"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>java8新特性 | Yorn's Notes</title>
  






  <noscript>
    <link rel="stylesheet" href="/myblog/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/myblog/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">Yorn's Notes</p>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-首页"><a href="/myblog/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-关于"><a href="/myblog/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a></li><li class="menu-item menu-item-标签"><a href="/myblog/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a></li><li class="menu-item menu-item-分类"><a href="/myblog/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li>
  </ul>
</nav>




</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#java-8-%E6%96%B0%E7%89%B9%E6%80%A7"><span class="nav-number">1.</span> <span class="nav-text">java 8 新特性</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-Lambda%E8%A1%A8%E8%BE%BE%E5%BC%8F"><span class="nav-number">1.0.1.</span> <span class="nav-text">1. Lambda表达式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-%E6%96%B9%E6%B3%95%E5%BC%95%E7%94%A8"><span class="nav-number">1.0.2.</span> <span class="nav-text">2. 方法引用</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-%E5%87%BD%E6%95%B0%E5%BC%8F%E6%8E%A5%E5%8F%A3"><span class="nav-number">1.0.3.</span> <span class="nav-text">3.函数式接口</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-%E9%BB%98%E8%AE%A4%E6%96%B9%E6%B3%95"><span class="nav-number">1.0.4.</span> <span class="nav-text">4.默认方法</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E9%9D%99%E6%80%81%E9%BB%98%E8%AE%A4%E6%96%B9%E6%B3%95"><span class="nav-number">1.0.4.1.</span> <span class="nav-text">静态默认方法</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E9%BB%98%E8%AE%A4%E6%96%B9%E6%B3%95%E5%AE%9E%E4%BE%8B"><span class="nav-number">1.0.4.2.</span> <span class="nav-text">默认方法实例</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-Stream"><span class="nav-number">1.0.5.</span> <span class="nav-text">5. Stream</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E4%BB%80%E4%B9%88%E6%98%AF-Stream%EF%BC%9F"><span class="nav-number">1.0.5.1.</span> <span class="nav-text">什么是 Stream？</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E7%94%9F%E6%88%90%E6%B5%81"><span class="nav-number">1.0.5.2.</span> <span class="nav-text">生成流</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#forEach"><span class="nav-number">1.0.5.3.</span> <span class="nav-text">forEach</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#map"><span class="nav-number">1.0.5.4.</span> <span class="nav-text">map</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#filter"><span class="nav-number">1.0.5.5.</span> <span class="nav-text">filter</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#limit"><span class="nav-number">1.0.5.6.</span> <span class="nav-text">limit</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#sorted"><span class="nav-number">1.0.5.7.</span> <span class="nav-text">sorted</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%B9%B6%E8%A1%8C%EF%BC%88parallel%EF%BC%89%E7%A8%8B%E5%BA%8F"><span class="nav-number">1.0.5.8.</span> <span class="nav-text">并行（parallel）程序</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Collectors"><span class="nav-number">1.0.5.9.</span> <span class="nav-text">Collectors</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E7%BB%9F%E8%AE%A1"><span class="nav-number">1.0.5.10.</span> <span class="nav-text">统计</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6-Java-8-Optional-%E7%B1%BB"><span class="nav-number">1.0.6.</span> <span class="nav-text">6.Java 8 Optional 类</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E7%B1%BB%E5%A3%B0%E6%98%8E"><span class="nav-number">1.0.6.1.</span> <span class="nav-text">类声明</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E7%B1%BB%E6%96%B9%E6%B3%95"><span class="nav-number">1.0.6.2.</span> <span class="nav-text">类方法</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#of-amp-amp-ofNullable"><span class="nav-number">1.0.7.</span> <span class="nav-text">of &amp;&amp; ofNullable</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#map-1"><span class="nav-number">1.0.8.</span> <span class="nav-text">map</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#%E4%BE%8B%E5%AD%90"><span class="nav-number">1.0.8.0.1.</span> <span class="nav-text">例子</span></a></li></ol></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Java-8-%E6%97%A5%E6%9C%9F%E6%97%B6%E9%97%B4-API"><span class="nav-number">1.0.9.</span> <span class="nav-text">Java 8 日期时间 API</span></a></li></ol></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="yorn"
      src="/myblog/uploads/head.jpg">
  <p class="site-author-name" itemprop="name">yorn</p>
  <div class="site-description" itemprop="description">足够专注才能成功</div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/myblog/archives/">
          <span class="site-state-item-count">53</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/myblog/categories/">
        <span class="site-state-item-count">13</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/myblog/tags/">
        <span class="site-state-item-count">19</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author site-overview-item animated">
      <span class="links-of-author-item">
        <a href="https://github.com/wang-chen1119" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;wang-chen1119" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:w1905989051@gmail.com" title="E-Mail → mailto:w1905989051@gmail.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>
  <div class="cc-license site-overview-item animated" itemprop="license">
    <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" class="cc-opacity" rel="noopener" target="_blank"><img src="https://cdnjs.cloudflare.com/ajax/libs/creativecommons-vocabulary/2020.11.3/assets/license_badges/small/by_nc_sa.svg" alt="Creative Commons"></a>
  </div>


  <div class="links-of-blogroll site-overview-item animated">
    <div class="links-of-blogroll-title"><i class="fa fa-globe fa-fw"></i>
      Links
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="https://blog.csdn.net/qq_51088445" title="https:&#x2F;&#x2F;blog.csdn.net&#x2F;qq_51088445" rel="noopener" target="_blank">CSDN</a>
        </li>
    </ul>
  </div>

        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>
  <a role="button" class="book-mark-link book-mark-link-fixed"></a>

  <a href="https://github.com/wang-chen1119" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://wang-chen1119.gitee.io/myblog/2022/10/28/java%208%20%E6%96%B0%E7%89%B9%E6%80%A7/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/myblog/uploads/head.jpg">
      <meta itemprop="name" content="yorn">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Yorn's Notes">
      <meta itemprop="description" content="足够专注才能成功">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="java8新特性 | Yorn's Notes">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          java8新特性
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>
      

      <time title="创建时间：2022-10-28 16:51:27 / 修改时间：16:52:02" itemprop="dateCreated datePublished" datetime="2022-10-28T16:51:27+08:00">2022-10-28</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/myblog/categories/java%E5%9F%BA%E7%A1%80/" itemprop="url" rel="index"><span itemprop="name">java基础</span></a>
        </span>
    </span>

  
    <span class="post-meta-break"></span>
    <span class="post-meta-item" title="本文字数">
      <span class="post-meta-item-icon">
        <i class="far fa-file-word"></i>
      </span>
      <span class="post-meta-item-text">本文字数：</span>
      <span>15k</span>
    </span>
    <span class="post-meta-item" title="阅读时长">
      <span class="post-meta-item-icon">
        <i class="far fa-clock"></i>
      </span>
      <span class="post-meta-item-text">阅读时长 &asymp;</span>
      <span>13 分钟</span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h1 id="java-8-新特性"><a href="#java-8-新特性" class="headerlink" title="java 8 新特性"></a>java 8 新特性</h1><h3 id="1-Lambda表达式"><a href="#1-Lambda表达式" class="headerlink" title="1. Lambda表达式"></a>1. Lambda表达式</h3><p>:book:  Lambda是一个匿名函数，让代码像数据一样进行传递，让代码更加简洁与灵活。</p>
<p>举例</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">LambdaTest</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">test1</span><span class="params">()</span>&#123;</span><br><span class="line">        <span class="type">Runnable</span> <span class="variable">r1</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Runnable</span>() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">run</span><span class="params">()</span> &#123;</span><br><span class="line">                System.out.println(<span class="string">&quot;测试&quot;</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;;</span><br><span class="line">        r1.run();</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;-----------&quot;</span>);</span><br><span class="line">        <span class="type">Runnable</span> <span class="variable">r2</span> <span class="operator">=</span> () -&gt; System.out.println(<span class="string">&quot;测试1&quot;</span>);</span><br><span class="line">        r2.run();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">test2</span><span class="params">()</span> &#123;</span><br><span class="line">        Comparator&lt;Integer&gt; com1 = <span class="keyword">new</span> <span class="title class_">Comparator</span>&lt;Integer&gt;() &#123;</span><br><span class="line"></span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="keyword">public</span> <span class="type">int</span> <span class="title function_">compare</span><span class="params">(Integer o1, Integer o2)</span> &#123;</span><br><span class="line">                <span class="keyword">return</span> Integer.compare(o1, o2);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;;</span><br><span class="line"></span><br><span class="line">        <span class="type">Integer</span> <span class="variable">flag</span> <span class="operator">=</span> com1.compare(<span class="number">22</span>,<span class="number">32</span>);</span><br><span class="line">        System.out.println(flag);</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;---------------&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 方法引用</span></span><br><span class="line">        Comparator&lt;Integer&gt; com2 = Integer::compare;</span><br><span class="line">        <span class="type">int</span> <span class="variable">flag1</span> <span class="operator">=</span> com2.compare(<span class="number">11</span>,<span class="number">22</span>);</span><br><span class="line"></span><br><span class="line">        System.out.println(flag1);</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;---------------&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// lambda表达式</span></span><br><span class="line">        Comparator&lt;Integer&gt; com3 = (o1,o2) -&gt; Integer.compare(o1,o2);</span><br><span class="line">        <span class="type">int</span> <span class="variable">flag2</span> <span class="operator">=</span> com3.compare(<span class="number">31</span>,<span class="number">22</span>);</span><br><span class="line"></span><br><span class="line">        System.out.println(flag2);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>



<p>格式</p>
<p>lambda操作符 或 箭头操作符</p>
<p>左边lambda形参列表（接口中的抽象方法的形参列表）</p>
<p>右边lambda体（重写的抽象方法的方法体）</p>
<p><strong>lambda的本质</strong></p>
<p>作为接口的实例   —&gt; lambda表达式借助接口存在</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">test3</span><span class="params">()</span>&#123;</span><br><span class="line">    StringOut so= (s) -&gt; &#123;</span><br><span class="line">        System.out.println(s);</span><br><span class="line">    &#125;;</span><br><span class="line">    so.accept(<span class="string">&quot;1&quot;</span>);</span><br><span class="line">    System.out.println(<span class="string">&quot;----------&quot;</span>);</span><br><span class="line">    StringOut so1= System.out::println;</span><br><span class="line">    so1.accept(<span class="string">&quot;2&quot;</span>);</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">interface</span> <span class="title class_">StringOut</span>&#123;</span><br><span class="line">   <span class="keyword">void</span> <span class="title function_">accept</span><span class="params">(String s)</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>





<h3 id="2-方法引用"><a href="#2-方法引用" class="headerlink" title="2. 方法引用"></a>2. 方法引用</h3><p>方法引用通过方法的名字来指向一个方法。</p>
<p>方法引用可以使语言的构造更紧凑简洁，减少冗余代码。</p>
<p>方法引用使用一对冒号 <strong>::</strong> 。</p>
<p><strong>举例</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line">   <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">test4</span><span class="params">()</span>&#123;</span><br><span class="line">       List&lt;String&gt; list = <span class="keyword">new</span> <span class="title class_">ArrayList</span>&lt;&gt;();</span><br><span class="line">       list.add(<span class="string">&quot;gouxiong&quot;</span>);</span><br><span class="line">       list.add(<span class="string">&quot;xiongmao&quot;</span>);</span><br><span class="line">       list.add(<span class="string">&quot;daishu&quot;</span>);</span><br><span class="line">       list.add(<span class="string">&quot;daoge&quot;</span>);</span><br><span class="line">       list.add(<span class="string">&quot;cat&quot;</span>);</span><br><span class="line">       list.forEach(System.out::println);</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>

<h3 id="3-函数式接口"><a href="#3-函数式接口" class="headerlink" title="3.函数式接口"></a>3.函数式接口</h3><p>函数式接口(Functional Interface)就是一个有且仅有一个抽象方法，但是可以有多个非抽象方法的接口。</p>
<p>函数式接口可以被隐式转换为 lambda 表达式。</p>
<p>Lambda 表达式和方法引用（实际上也可认为是Lambda表达式）上。</p>
<p>如定义了一个函数式接口如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@FunctionalInterface</span></span><br><span class="line"><span class="keyword">interface</span> <span class="title class_">GreetingService</span> </span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">void</span> <span class="title function_">sayMessage</span><span class="params">(String message)</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>那么就可以使用Lambda表达式来表示该接口的一个实现(注：JAVA 8 之前一般是用匿名类实现的)：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">GreetingService</span> <span class="variable">greetService1</span> <span class="operator">=</span> message -&gt; System.out.println(<span class="string">&quot;Hello &quot;</span> + message);</span><br></pre></td></tr></table></figure>

<p>​	</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">test5</span><span class="params">()</span>&#123;</span><br><span class="line">        <span class="type">Experiment</span> <span class="variable">e1</span> <span class="operator">=</span> message-&gt; System.out.println(<span class="string">&quot;这是个测试&quot;</span>+message);</span><br><span class="line">        e1.sayMessage(<span class="string">&quot;111&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="meta">@FunctionalInterface</span></span><br><span class="line">    <span class="keyword">interface</span> <span class="title class_">Experiment</span>&#123;</span><br><span class="line">        <span class="keyword">void</span> <span class="title function_">sayMessage</span><span class="params">(String s)</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>JDK 1.8 之前已有的函数式接口:</p>
<ul>
<li>java.lang.Runnable</li>
<li>java.util.concurrent.Callable</li>
<li>java.security.PrivilegedAction</li>
<li>java.util.Comparator</li>
<li>java.io.FileFilter</li>
<li>java.nio.file.PathMatcher</li>
<li>java.lang.reflect.InvocationHandler</li>
<li>java.beans.PropertyChangeListener</li>
<li>java.awt.event.ActionListener</li>
<li>javax.swing.event.ChangeListener</li>
</ul>
<p>JDK 1.8 新增加的函数接口：</p>
<ul>
<li>java.util.function</li>
</ul>
<p>java.util.function 它包含了很多类，用来支持 Java的 函数式编程，该包中的函数式接口有：</p>
<table>
<thead>
<tr>
<th align="left">序号</th>
<th align="left">接口 &amp; 描述</th>
</tr>
</thead>
<tbody><tr>
<td align="left">1</td>
<td align="left">**BiConsumer&lt;T,U&gt;**代表了一个接受两个输入参数的操作，并且不返回任何结果</td>
</tr>
<tr>
<td align="left">2</td>
<td align="left">**BiFunction&lt;T,U,R&gt;**代表了一个接受两个输入参数的方法，并且返回一个结果</td>
</tr>
<tr>
<td align="left">3</td>
<td align="left">**BinaryOperator<T>**代表了一个作用于于两个同类型操作符的操作，并且返回了操作符同类型的结果</td>
</tr>
<tr>
<td align="left">4</td>
<td align="left">**BiPredicate&lt;T,U&gt;**代表了一个两个参数的boolean值方法</td>
</tr>
<tr>
<td align="left">5</td>
<td align="left"><strong>BooleanSupplier</strong>代表了boolean值结果的提供方</td>
</tr>
<tr>
<td align="left">6</td>
<td align="left">**Consumer<T>**代表了接受一个输入参数并且无返回的操作</td>
</tr>
<tr>
<td align="left">7</td>
<td align="left"><strong>DoubleBinaryOperator</strong>代表了作用于两个double值操作符的操作，并且返回了一个double值的结果。</td>
</tr>
<tr>
<td align="left">8</td>
<td align="left"><strong>DoubleConsumer</strong>代表一个接受double值参数的操作，并且不返回结果。</td>
</tr>
<tr>
<td align="left">9</td>
<td align="left">**DoubleFunction<R>**代表接受一个double值参数的方法，并且返回结果</td>
</tr>
<tr>
<td align="left">10</td>
<td align="left"><strong>DoublePredicate</strong>代表一个拥有double值参数的boolean值方法</td>
</tr>
<tr>
<td align="left">11</td>
<td align="left"><strong>DoubleSupplier</strong>代表一个double值结构的提供方</td>
</tr>
<tr>
<td align="left">12</td>
<td align="left"><strong>DoubleToIntFunction</strong>接受一个double类型输入，返回一个int类型结果。</td>
</tr>
<tr>
<td align="left">13</td>
<td align="left"><strong>DoubleToLongFunction</strong>接受一个double类型输入，返回一个long类型结果</td>
</tr>
<tr>
<td align="left">14</td>
<td align="left"><strong>DoubleUnaryOperator</strong>接受一个参数同为类型double,返回值类型也为double 。</td>
</tr>
<tr>
<td align="left">15</td>
<td align="left">**Function&lt;T,R&gt;**接受一个输入参数，返回一个结果。</td>
</tr>
<tr>
<td align="left">16</td>
<td align="left"><strong>IntBinaryOperator</strong>接受两个参数同为类型int,返回值类型也为int 。</td>
</tr>
<tr>
<td align="left">17</td>
<td align="left"><strong>IntConsumer</strong>接受一个int类型的输入参数，无返回值 。</td>
</tr>
<tr>
<td align="left">18</td>
<td align="left">**IntFunction<R>**接受一个int类型输入参数，返回一个结果 。</td>
</tr>
<tr>
<td align="left">19</td>
<td align="left"><strong>IntPredicate</strong>：接受一个int输入参数，返回一个布尔值的结果。</td>
</tr>
<tr>
<td align="left">20</td>
<td align="left"><strong>IntSupplier</strong>无参数，返回一个int类型结果。</td>
</tr>
<tr>
<td align="left">21</td>
<td align="left"><strong>IntToDoubleFunction</strong>接受一个int类型输入，返回一个double类型结果 。</td>
</tr>
<tr>
<td align="left">22</td>
<td align="left"><strong>IntToLongFunction</strong>接受一个int类型输入，返回一个long类型结果。</td>
</tr>
<tr>
<td align="left">23</td>
<td align="left"><strong>IntUnaryOperator</strong>接受一个参数同为类型int,返回值类型也为int 。</td>
</tr>
<tr>
<td align="left">24</td>
<td align="left"><strong>LongBinaryOperator</strong>接受两个参数同为类型long,返回值类型也为long。</td>
</tr>
<tr>
<td align="left">25</td>
<td align="left"><strong>LongConsumer</strong>接受一个long类型的输入参数，无返回值。</td>
</tr>
<tr>
<td align="left">26</td>
<td align="left">**LongFunction<R>**接受一个long类型输入参数，返回一个结果。</td>
</tr>
<tr>
<td align="left">27</td>
<td align="left"><strong>LongPredicate</strong>R接受一个long输入参数，返回一个布尔值类型结果。</td>
</tr>
<tr>
<td align="left">28</td>
<td align="left"><strong>LongSupplier</strong>无参数，返回一个结果long类型的值。</td>
</tr>
<tr>
<td align="left">29</td>
<td align="left"><strong>LongToDoubleFunction</strong>接受一个long类型输入，返回一个double类型结果。</td>
</tr>
<tr>
<td align="left">30</td>
<td align="left"><strong>LongToIntFunction</strong>接受一个long类型输入，返回一个int类型结果。</td>
</tr>
<tr>
<td align="left">31</td>
<td align="left"><strong>LongUnaryOperator</strong>接受一个参数同为类型long,返回值类型也为long。</td>
</tr>
<tr>
<td align="left">32</td>
<td align="left">**ObjDoubleConsumer<T>**接受一个object类型和一个double类型的输入参数，无返回值。</td>
</tr>
<tr>
<td align="left">33</td>
<td align="left">**ObjIntConsumer<T>**接受一个object类型和一个int类型的输入参数，无返回值。</td>
</tr>
<tr>
<td align="left">34</td>
<td align="left">**ObjLongConsumer<T>**接受一个object类型和一个long类型的输入参数，无返回值。</td>
</tr>
<tr>
<td align="left">35</td>
<td align="left">**Predicate<T>**接受一个输入参数，返回一个布尔值结果。</td>
</tr>
<tr>
<td align="left">36</td>
<td align="left">**Supplier<T>**无参数，返回一个结果。</td>
</tr>
<tr>
<td align="left">37</td>
<td align="left">**ToDoubleBiFunction&lt;T,U&gt;**接受两个输入参数，返回一个double类型结果</td>
</tr>
<tr>
<td align="left">38</td>
<td align="left">**ToDoubleFunction<T>**接受一个输入参数，返回一个double类型结果</td>
</tr>
<tr>
<td align="left">39</td>
<td align="left">**ToIntBiFunction&lt;T,U&gt;**接受两个输入参数，返回一个int类型结果。</td>
</tr>
<tr>
<td align="left">40</td>
<td align="left">**ToIntFunction<T>**接受一个输入参数，返回一个int类型结果。</td>
</tr>
<tr>
<td align="left">41</td>
<td align="left">**ToLongBiFunction&lt;T,U&gt;**接受两个输入参数，返回一个long类型结果。</td>
</tr>
<tr>
<td align="left">42</td>
<td align="left">**ToLongFunction<T>**接受一个输入参数，返回一个long类型结果。</td>
</tr>
<tr>
<td align="left">43</td>
<td align="left">**UnaryOperator<T>**接受一个参数为类型T,返回值类型也为T。</td>
</tr>
</tbody></table>
<p><strong>例子</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"> <span class="meta">@Test</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">test5</span><span class="params">()</span>&#123;</span><br><span class="line">        List&lt;Integer&gt; list = Arrays.asList(<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>,<span class="number">6</span>,<span class="number">7</span>,<span class="number">8</span>,<span class="number">9</span>);</span><br><span class="line">        eval(list,n-&gt;n%<span class="number">2</span> == <span class="number">0</span>);</span><br><span class="line">        eval(list,n-&gt;n&gt;<span class="number">3</span>);</span><br><span class="line">        eval(list,n-&gt;n%<span class="number">3</span> == <span class="number">0</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">eval</span><span class="params">(List&lt;Integer&gt;list, Predicate&lt;Integer&gt; predicate)</span>&#123;</span><br><span class="line">        <span class="keyword">for</span> (Integer n : list) &#123;</span><br><span class="line">            <span class="keyword">if</span> (predicate.test(n)) &#123;</span><br><span class="line">                System.out.println(n);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="4-默认方法"><a href="#4-默认方法" class="headerlink" title="4.默认方法"></a>4.默认方法</h3><blockquote>
<p>Java 8 新增了接口的默认方法。</p>
<p>简单说，默认方法就是接口可以有实现方法，而且不需要实现类去实现其方法。</p>
<p>我们只需在方法名前面加个 default 关键字即可实现默认方法。</p>
</blockquote>
<p>:books:<strong>为什么会出现默认方法？</strong></p>
<p>java8之前如果需要修改接口功能通常需要在接口中添加方法，而已经实现该接口的类都需要将此方法实现。</p>
<p>默认方法的出现使___接口在定义新方法的同时又不会影响到实现类___</p>
<p><strong>使用</strong></p>
<p>默认方法的实例</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">interface</span> <span class="title class_">TestInterface1</span>&#123;</span><br><span class="line">    <span class="keyword">default</span> <span class="keyword">void</span> <span class="title function_">sayMessage</span><span class="params">()</span>&#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;测试接口1&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>实现的多个接口具有相同的默认方法</p>
<p>解决方案：</p>
<ol>
<li>实现这两个接口的类重写该方法</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">interface</span> <span class="title class_">TestInterface1</span>&#123;</span><br><span class="line">     <span class="keyword">default</span> <span class="keyword">void</span> <span class="title function_">sayMessage</span><span class="params">()</span>&#123;</span><br><span class="line">         System.out.println(<span class="string">&quot;测试接口1&quot;</span>);</span><br><span class="line">     &#125;</span><br><span class="line"> &#125;</span><br><span class="line"></span><br><span class="line"> <span class="keyword">interface</span> <span class="title class_">TestInterface2</span>&#123;</span><br><span class="line">     <span class="keyword">default</span> <span class="keyword">void</span> <span class="title function_">sayMessage</span><span class="params">()</span>&#123;</span><br><span class="line">         System.out.println(<span class="string">&quot;测试接口2&quot;</span>);</span><br><span class="line">     &#125;</span><br><span class="line"> &#125;</span><br><span class="line"> </span><br><span class="line"> <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">class</span> <span class="title class_">TestClass</span> <span class="keyword">implements</span> <span class="title class_">TestInterface1</span> ,TestInterface2 &#123;</span><br><span class="line"></span><br><span class="line">     <span class="meta">@Override</span></span><br><span class="line">     <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">sayMessage</span><span class="params">()</span> &#123;</span><br><span class="line">         System.out.println(<span class="string">&quot;重写&quot;</span>);</span><br><span class="line">     &#125;</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>

<ol start="2">
<li>super调用指定接口的方法</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">    <span class="keyword">interface</span> <span class="title class_">TestInterface1</span>&#123;</span><br><span class="line">        <span class="keyword">default</span> <span class="keyword">void</span> <span class="title function_">sayMessage</span><span class="params">()</span>&#123;</span><br><span class="line">            System.out.println(<span class="string">&quot;测试接口1&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">interface</span> <span class="title class_">TestInterface2</span>&#123;</span><br><span class="line">        <span class="keyword">default</span> <span class="keyword">void</span> <span class="title function_">sayMessage</span><span class="params">()</span>&#123;</span><br><span class="line">            System.out.println(<span class="string">&quot;测试接口2&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">class</span> <span class="title class_">TestClass</span> <span class="keyword">implements</span> <span class="title class_">TestInterface1</span> ,TestInterface2 &#123;</span><br><span class="line"></span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">sayMessage</span><span class="params">()</span> &#123;</span><br><span class="line">            TestInterface1.<span class="built_in">super</span>.sayMessage();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="静态默认方法"><a href="#静态默认方法" class="headerlink" title="静态默认方法"></a>静态默认方法</h4><p>java8支持接口定义静态默认方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">staticMethod</span><span class="params">()</span>&#123;</span><br><span class="line">    System.out.println(<span class="string">&quot;静态默认方法&quot;</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="默认方法实例"><a href="#默认方法实例" class="headerlink" title="默认方法实例"></a>默认方法实例</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line">    <span class="keyword">interface</span> <span class="title class_">TestInterface1</span>&#123;</span><br><span class="line">        <span class="keyword">default</span> <span class="keyword">void</span> <span class="title function_">sayMessage</span><span class="params">()</span>&#123;</span><br><span class="line">            System.out.println(<span class="string">&quot;测试接口1&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">staticMethod</span><span class="params">()</span>&#123;</span><br><span class="line">            System.out.println(<span class="string">&quot;静态默认方法&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">interface</span> <span class="title class_">TestInterface2</span>&#123;</span><br><span class="line">        <span class="keyword">default</span> <span class="keyword">void</span> <span class="title function_">sayMessage</span><span class="params">()</span>&#123;</span><br><span class="line">            System.out.println(<span class="string">&quot;测试接口2&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">class</span> <span class="title class_">TestClass</span> <span class="keyword">implements</span> <span class="title class_">TestInterface1</span> ,TestInterface2 &#123;</span><br><span class="line"></span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">sayMessage</span><span class="params">()</span> &#123;</span><br><span class="line">            TestInterface1.<span class="built_in">super</span>.sayMessage();</span><br><span class="line">            TestInterface2.<span class="built_in">super</span>.sayMessage();</span><br><span class="line">            TestInterface1.staticMethod();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">test6</span><span class="params">()</span>&#123;</span><br><span class="line">        <span class="type">TestInterface1</span> <span class="variable">test</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">TestClass</span>();</span><br><span class="line">        test.sayMessage();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>





<h3 id="5-Stream"><a href="#5-Stream" class="headerlink" title="5. Stream"></a>5. Stream</h3><blockquote>
<p>Java 8 API添加了一个新的抽象称为流Stream，可以让你以一种声明的方式处理数据。</p>
<p>Stream 使用一种类似用 SQL 语句从数据库查询数据的直观方式来提供一种对 Java 集合运算和表达的高阶抽象。</p>
<p>Stream API可以极大提高Java程序员的生产力，让程序员写出高效率、干净、简洁的代码。</p>
<p>这种风格将要处理的元素集合看作一种流， 流在管道中传输， 并且可以在管道的节点上进行处理， 比如筛选， 排序，聚合等。</p>
<p>元素流在管道中经过中间操作（intermediate operation）的处理，最后由最终操作(terminal operation)得到前面处理的结果。</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">+--------------------+       +------+   +------+   +---+   +-------+</span><br><span class="line">| stream of elements +-----&gt; |filter+-&gt; |sorted+-&gt; |map+-&gt; |collect|</span><br><span class="line">+--------------------+       +------+   +------+   +---+   +-------+</span><br></pre></td></tr></table></figure>

<h4 id="什么是-Stream？"><a href="#什么是-Stream？" class="headerlink" title="什么是 Stream？"></a>什么是 Stream？</h4><p>Stream（流）是一个来自数据源的元素队列并支持聚合操作</p>
<ul>
<li>元素是特定类型的对象，形成一个队列。 Java中的Stream并不会存储元素，而是按需计算。</li>
<li><strong>数据源</strong> 流的来源。 可以是集合，数组，I&#x2F;O channel， 产生器generator 等。</li>
<li><strong>聚合操作</strong> 类似SQL语句一样的操作， 比如filter, map, reduce, find, match, sorted等。</li>
</ul>
<p>和以前的Collection操作不同， Stream操作还有两个基础的特征：</p>
<ul>
<li><p><strong>Pipelining</strong>: 中间操作都会返回流对象本身。 这样多个操作可以串联成一个管道， 如同流式风格（fluent style）。 这样做可以对操作进行优化， 比如延迟执行(laziness)和短路( short-circuiting)。</p>
</li>
<li><p><strong>内部迭代</strong>： 以前对集合遍历都是通过Iterator或者For-Each的方式, 显式的在集合外部进行迭代， 这叫做外部迭代。 Stream提供了内部迭代的方式， 通过访问者模式(Visitor)实现。</p>
<hr>
</li>
</ul>
<h4 id="生成流"><a href="#生成流" class="headerlink" title="生成流"></a>生成流</h4><p>在 Java 8 中, 集合接口有两个方法来生成流：</p>
<ul>
<li><strong>stream()</strong> − 为集合创建串行流。</li>
<li><strong>parallelStream()</strong> − 为集合创建并行流。</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">List&lt;String&gt; strings = Arrays.asList(<span class="string">&quot;abc&quot;</span>, <span class="string">&quot;&quot;</span>, <span class="string">&quot;bc&quot;</span>, <span class="string">&quot;efg&quot;</span>, <span class="string">&quot;abcd&quot;</span>,<span class="string">&quot;&quot;</span>, <span class="string">&quot;jkl&quot;</span>); List&lt;String&gt; filtered = strings.stream().filter(string -&gt; !string.isEmpty()).collect(Collectors.toList());</span><br></pre></td></tr></table></figure>

<hr>
<h4 id="forEach"><a href="#forEach" class="headerlink" title="forEach"></a>forEach</h4><p>Stream 提供了新的方法 ‘forEach’ 来迭代流中的每个数据。以下代码片段使用 forEach 输出了10个随机数：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">Random</span> <span class="variable">random</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Random</span>(); </span><br><span class="line">random.ints().limit(<span class="number">10</span>).forEach(System.out::println);</span><br></pre></td></tr></table></figure>

<hr>
<h4 id="map"><a href="#map" class="headerlink" title="map"></a>map</h4><p>map 方法用于映射每个元素到对应的结果，以下代码片段使用 map 输出了元素对应的平方数：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">List&lt;Integer&gt; numbers = Arrays.asList(<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>,<span class="number">6</span>,<span class="number">7</span>,<span class="number">8</span>,<span class="number">9</span>);</span><br><span class="line">List&lt;Integer&gt; res = numbers.stream().map(i-&gt;i*i).collect(Collectors.toList());</span><br><span class="line">res.forEach(System.out::println);</span><br></pre></td></tr></table></figure>

<hr>
<h4 id="filter"><a href="#filter" class="headerlink" title="filter"></a>filter</h4><p>filter 方法用于通过设置的条件过滤出元素。以下代码片段使用 filter 方法过滤出空字符串：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">List&lt;String&gt; stringList = Arrays.asList(<span class="string">&quot;&quot;</span>,<span class="string">&quot;&quot;</span>,<span class="string">&quot;1&quot;</span>,<span class="string">&quot;2&quot;</span>,<span class="string">&quot;&quot;</span>,<span class="string">&quot;3&quot;</span>);</span><br><span class="line"><span class="type">Long</span> <span class="variable">num</span> <span class="operator">=</span> stringList.stream().filter(String::isEmpty).count();</span><br><span class="line">System.out.println(num);</span><br></pre></td></tr></table></figure>

<h4 id="limit"><a href="#limit" class="headerlink" title="limit"></a>limit</h4><p>limit 方法用于获取指定数量的流。 以下代码片段使用 limit 方法打印出 10 条数据：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">Random</span> <span class="variable">random</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Random</span>();</span><br><span class="line"> random.ints().limit(<span class="number">10</span>).forEach(System.out::println);</span><br></pre></td></tr></table></figure>

<hr>
<h4 id="sorted"><a href="#sorted" class="headerlink" title="sorted"></a>sorted</h4><p>sorted 方法用于对流进行排序。以下代码片段使用 sorted 方法对输出的 10 个随机数进行排序：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">numbers.stream().limit(<span class="number">5</span>).sorted().forEach(System.out::println);</span><br></pre></td></tr></table></figure>

<hr>
<h4 id="并行（parallel）程序"><a href="#并行（parallel）程序" class="headerlink" title="并行（parallel）程序"></a>并行（parallel）程序</h4><p>parallelStream 是流并行处理程序的代替方法。以下实例我们使用 parallelStream 来输出空字符串的数量：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">List&lt;String&gt; strings = Arrays.asList(<span class="string">&quot;abc&quot;</span>, <span class="string">&quot;&quot;</span>, <span class="string">&quot;bc&quot;</span>, <span class="string">&quot;efg&quot;</span>, <span class="string">&quot;abcd&quot;</span>,<span class="string">&quot;&quot;</span>, <span class="string">&quot;jkl&quot;</span>); <span class="comment">// 获取空字符串的数量</span></span><br><span class="line"><span class="type">long</span> <span class="variable">count</span> <span class="operator">=</span> strings.parallelStream().filter(string -&gt; string.isEmpty()).count();</span><br></pre></td></tr></table></figure>

<p>我们可以很容易的在顺序运行和并行直接切换。</p>
<hr>
<h4 id="Collectors"><a href="#Collectors" class="headerlink" title="Collectors"></a>Collectors</h4><p>Collectors 类实现了很多归约操作，例如将流转换成集合和聚合元素。Collectors 可用于返回列表或字符串：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">List&lt;String&gt; res1 = stringList.stream().filter(String::isEmpty).collect(Collectors.toList());</span><br><span class="line">System.out.println(res1);</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">String</span> <span class="variable">res2</span> <span class="operator">=</span> stringList.stream().filter(s-&gt;!s.isEmpty()).collect(Collectors.joining(<span class="string">&quot;,&quot;</span>));</span><br></pre></td></tr></table></figure>

<hr>
<h4 id="统计"><a href="#统计" class="headerlink" title="统计"></a>统计</h4><p>另外，一些产生统计结果的收集器也非常有用。它们主要用于int、double、long等基本类型上，它们可以用来产生类似如下的统计结果。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">IntSummaryStatistics</span> <span class="variable">stats</span> <span class="operator">=</span> numbers.stream().mapToInt((x) -&gt; x).summaryStatistics();</span><br><span class="line">System.out.println(<span class="string">&quot;列表中最大的数 : &quot;</span> + stats.getMax());</span><br><span class="line">System.out.println(<span class="string">&quot;列表中最小的数 : &quot;</span> + stats.getMin());</span><br><span class="line">System.out.println(<span class="string">&quot;所有数之和 : &quot;</span> + stats.getSum());</span><br><span class="line">System.out.println(<span class="string">&quot;平均数 : &quot;</span> + stats.getAverage());</span><br></pre></td></tr></table></figure>







<h3 id="6-Java-8-Optional-类"><a href="#6-Java-8-Optional-类" class="headerlink" title="6.Java 8 Optional 类"></a>6.Java 8 Optional 类</h3><p>:books:<strong>optional类出现的意义？</strong></p>
<p>Optional 类的出现能够更好地___解决空指针异常___</p>
<blockquote>
<p>Optional 类是一个可以为null的容器对象。如果值存在则isPresent()方法会返回true，调用get()方法会返回该对象。</p>
<p>Optional 是个容器：它可以保存类型T的值，或者仅仅保存null。Optional提供很多有用的方法，这样我们就不用显式进行空值检测。</p>
</blockquote>
<h4 id="类声明"><a href="#类声明" class="headerlink" title="类声明"></a>类声明</h4><p>以下是一个 <strong>java.util.Optional<T></strong> 类的声明：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">class</span> <span class="title class_">Optional</span>&lt;T&gt; <span class="keyword">extends</span> <span class="title class_">Object</span></span><br></pre></td></tr></table></figure>

<h4 id="类方法"><a href="#类方法" class="headerlink" title="类方法"></a>类方法</h4><table>
<thead>
<tr>
<th align="left">序号</th>
<th align="left">方法 &amp; 描述</th>
</tr>
</thead>
<tbody><tr>
<td align="left">1</td>
<td align="left">**static <T> Optional<T> empty()**返回空的 Optional 实例。</td>
</tr>
<tr>
<td align="left">2</td>
<td align="left">**boolean equals(Object obj)**判断其他对象是否等于 Optional。</td>
</tr>
<tr>
<td align="left">3</td>
<td align="left">**Optional<T> filter(Predicate&lt;? super <T> predicate)**如果值存在，并且这个值匹配给定的 predicate，返回一个Optional用以描述这个值，否则返回一个空的Optional。</td>
</tr>
<tr>
<td align="left">4</td>
<td align="left">**<U> Optional<U> flatMap(Function&lt;? super T,Optional<U>&gt; mapper)**如果值存在，返回基于Optional包含的映射方法的值，否则返回一个空的Optional</td>
</tr>
<tr>
<td align="left">5</td>
<td align="left">**T get()**如果在这个Optional中包含这个值，返回值，否则抛出异常：NoSuchElementException</td>
</tr>
<tr>
<td align="left">6</td>
<td align="left">**int hashCode()**返回存在值的哈希码，如果值不存在 返回 0。</td>
</tr>
<tr>
<td align="left">7</td>
<td align="left">**void ifPresent(Consumer&lt;? super T&gt; consumer)**如果值存在则使用该值调用 consumer , 否则不做任何事情。</td>
</tr>
<tr>
<td align="left">8</td>
<td align="left">**boolean isPresent()**如果值存在则方法会返回true，否则返回 false。</td>
</tr>
<tr>
<td align="left">9</td>
<td align="left">**<U>Optional<U> map(Function&lt;? super T,? extends U&gt; mapper)**如果有值，则对其执行调用映射函数得到返回值。如果返回值不为 null，则创建包含映射返回值的Optional作为map方法返回值，否则返回空Optional。</td>
</tr>
<tr>
<td align="left">10</td>
<td align="left">**static <T> Optional<T> of(T value)**返回一个指定非null值的Optional。</td>
</tr>
<tr>
<td align="left">11</td>
<td align="left">**static <T> Optional<T> ofNullable(T value)**如果为非空，返回 Optional 描述的指定值，否则返回空的 Optional。</td>
</tr>
<tr>
<td align="left">12</td>
<td align="left">**T orElse(T other)**如果存在该值，返回值， 否则返回 other。</td>
</tr>
<tr>
<td align="left">13</td>
<td align="left">**T orElseGet(Supplier&lt;? extends T&gt; other)**如果存在该值，返回值， 否则触发 other，并返回 other 调用的结果。</td>
</tr>
<tr>
<td align="left">14</td>
<td align="left">**<X extends Throwable> T orElseThrow(Supplier&lt;? extends X&gt; exceptionSupplier)**如果存在该值，返回包含的值，否则抛出由 Supplier 继承的异常</td>
</tr>
<tr>
<td align="left">15</td>
<td align="left">**String toString()**返回一个Optional的非空字符串，用来调试</td>
</tr>
</tbody></table>
<p>我们可以看到Optional总共也就10+个方法，其中有三个<strong>static</strong>方法。并且Optional的构造方法是private，不能new出来。</p>
<p>所以我们一般用这三个static来获取Optional的对象。</p>
<ul>
<li><h3 id="of-amp-amp-ofNullable"><a href="#of-amp-amp-ofNullable" class="headerlink" title="of &amp;&amp; ofNullable"></a>of &amp;&amp; ofNullable</h3></li>
</ul>
<p><a href="javascript:void(0);"><img src="/myblog/java%208%20%E6%96%B0%E7%89%B9%E6%80%A7.assets/copycode.gif" alt="复制代码"></a></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span> <span class="keyword">public</span> <span class="keyword">static</span> &lt;T&gt; Optional&lt;T&gt; <span class="title function_">of</span><span class="params">(T value)</span> &#123;</span><br><span class="line"><span class="number">2</span>     <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Optional</span>&lt;&gt;(value);</span><br><span class="line"><span class="number">3</span> &#125;</span><br><span class="line"><span class="number">4</span> </span><br><span class="line"><span class="number">5</span> <span class="keyword">public</span> <span class="keyword">static</span> &lt;T&gt; Optional&lt;T&gt; <span class="title function_">ofNullable</span><span class="params">(T value)</span> &#123;</span><br><span class="line"><span class="number">6</span>     <span class="keyword">return</span> value == <span class="literal">null</span> ? empty() : of(value);</span><br><span class="line"><span class="number">7</span> &#125;</span><br></pre></td></tr></table></figure>

<p><a href="javascript:void(0);"><img src="/myblog/java%208%20%E6%96%B0%E7%89%B9%E6%80%A7.assets/copycode.gif" alt="复制代码"></a></p>
<p>很明显 of 对null对象没有做任何处理，ofNullable才做了处理。所以当我们<strong>不知道传入的对象是否为null的时候</strong>，我们应该选择用 ofNullable来做处理。</p>
<ul>
<li><h3 id="map-1"><a href="#map-1" class="headerlink" title="map"></a>map</h3></li>
</ul>
<p><a href="javascript:void(0);"><img src="/myblog/java%208%20%E6%96%B0%E7%89%B9%E6%80%A7.assets/copycode.gif" alt="复制代码"></a></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span> <span class="keyword">public</span>&lt;U&gt; Optional&lt;U&gt; <span class="title function_">map</span><span class="params">(Function&lt;? <span class="built_in">super</span> T, ? extends U&gt; mapper)</span> &#123;</span><br><span class="line"><span class="number">2</span>     Objects.requireNonNull(mapper);</span><br><span class="line"><span class="number">3</span>     <span class="keyword">if</span> (!isPresent())</span><br><span class="line"><span class="number">4</span>         <span class="keyword">return</span> empty();</span><br><span class="line"><span class="number">5</span>     <span class="keyword">else</span> &#123;</span><br><span class="line"><span class="number">6</span>         <span class="keyword">return</span> Optional.ofNullable(mapper.apply(value));</span><br><span class="line"><span class="number">7</span>     &#125;</span><br><span class="line"><span class="number">8</span> &#125;</span><br></pre></td></tr></table></figure>

<p><a href="javascript:void(0);"><img src="/myblog/java%208%20%E6%96%B0%E7%89%B9%E6%80%A7.assets/copycode.gif" alt="复制代码"></a></p>
<p>如果我们想获取Object里面的值的话，我们就需要用到这个map。</p>
<h5 id="例子"><a href="#例子" class="headerlink" title="例子"></a>例子</h5><p><a href="javascript:void(0);"><img src="/myblog/java%208%20%E6%96%B0%E7%89%B9%E6%80%A7.assets/copycode.gif" alt="复制代码"></a></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"> <span class="number">1</span> <span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">OptionalTest</span> &#123;</span><br><span class="line"> <span class="number">2</span>     <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line"> <span class="number">3</span>         <span class="type">Person</span> <span class="variable">person</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Person</span>(<span class="string">&quot;zhangsan&quot;</span>, <span class="number">18</span>);</span><br><span class="line"> <span class="number">4</span>         <span class="type">String</span> <span class="variable">name</span> <span class="operator">=</span> getName(person);</span><br><span class="line"> <span class="number">5</span>         System.out.println(name);</span><br><span class="line"> <span class="number">6</span>     &#125;</span><br><span class="line"> <span class="number">7</span> </span><br><span class="line"> <span class="number">8</span>     <span class="keyword">private</span> <span class="keyword">static</span> String <span class="title function_">getName</span><span class="params">(Person person)</span> &#123;</span><br><span class="line"> <span class="number">9</span>         <span class="keyword">if</span> (Objects.isNull(person)) &#123;</span><br><span class="line"><span class="number">10</span>             <span class="keyword">return</span> <span class="string">&quot;unKnown&quot;</span>;</span><br><span class="line"><span class="number">11</span>         &#125;</span><br><span class="line"><span class="number">12</span>         <span class="keyword">return</span> person.getName();</span><br><span class="line"><span class="number">13</span>     &#125;</span><br><span class="line"><span class="number">14</span> </span><br><span class="line"><span class="number">15</span> &#125;</span><br></pre></td></tr></table></figure>

<p><a href="javascript:void(0);"><img src="/myblog/java%208%20%E6%96%B0%E7%89%B9%E6%80%A7.assets/copycode.gif" alt="复制代码"></a></p>
<p>我们看上面的这个例子。</p>
<p>我们有一个函数 <strong>getName</strong> 作用是获取Person对象的名字。但我并不知道这个Person是否为Null。</p>
<p>所以我要进行一个判断，判断Person是否为空，在做决定。</p>
<p>但如果我们使用Optional类的话，我们可以这样写</p>
<p><a href="javascript:void(0);"><img src="/myblog/java%208%20%E6%96%B0%E7%89%B9%E6%80%A7.assets/copycode.gif" alt="复制代码"></a></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"> <span class="number">1</span> <span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">OptionalTest</span> &#123;</span><br><span class="line"> <span class="number">2</span>     <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line"> <span class="number">3</span>         <span class="type">Person</span> <span class="variable">person</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Person</span>(<span class="string">&quot;zhangsan&quot;</span>, <span class="number">18</span>);</span><br><span class="line"> <span class="number">4</span>         <span class="type">String</span> <span class="variable">name</span> <span class="operator">=</span> getName(person);</span><br><span class="line"> <span class="number">5</span>         System.out.println(name);</span><br><span class="line"> <span class="number">6</span>     &#125;</span><br><span class="line"> <span class="number">7</span> </span><br><span class="line"> <span class="number">8</span>     <span class="keyword">private</span> <span class="keyword">static</span> String <span class="title function_">getName</span><span class="params">(Person person)</span> &#123;</span><br><span class="line"> <span class="number">9</span>         <span class="type">String</span> <span class="variable">name</span> <span class="operator">=</span> Optional.ofNullable(person).map(x -&gt; x.getName())</span><br><span class="line"><span class="number">10</span>                 .orElse(<span class="string">&quot;unKnown&quot;</span>);</span><br><span class="line"><span class="number">11</span>         <span class="keyword">return</span> name;</span><br><span class="line"><span class="number">12</span>     &#125;</span><br><span class="line"><span class="number">13</span> &#125;</span><br></pre></td></tr></table></figure>

<p><a href="javascript:void(0);"><img src="/myblog/java%208%20%E6%96%B0%E7%89%B9%E6%80%A7.assets/copycode.gif" alt="复制代码"></a></p>
<p>如果传入的为空，它会自动new一个 <strong>Optional<T> t &#x3D; (Optional<T>) EMPTY;</strong> </p>
<p>有效的处理到了null的问题，而且还非常的简洁。</p>
<h3 id="Java-8-日期时间-API"><a href="#Java-8-日期时间-API" class="headerlink" title="Java 8 日期时间 API"></a>Java 8 日期时间 API</h3><hr>
<p>Java 8通过发布新的Date-Time API (JSR 310)来进一步加强对日期与时间的处理。</p>
<p>在旧版的 Java 中，日期时间 API 存在诸多问题，其中有：</p>
<ul>
<li><strong>非线程安全</strong> − java.util.Date 是非线程安全的，所有的日期类都是可变的，这是Java日期类最大的问题之一。</li>
<li><strong>设计很差</strong> − Java的日期&#x2F;时间类的定义并不一致，在java.util和java.sql的包中都有日期类，此外用于格式化和解析的类在java.text包中定义。java.util.Date同时包含日期和时间，而java.sql.Date仅包含日期，将其纳入java.sql包并不合理。另外这两个类都有相同的名字，这本身就是一个非常糟糕的设计。</li>
<li><strong>时区处理麻烦</strong> − 日期类并不提供国际化，没有时区支持，因此Java引入了java.util.Calendar和java.util.TimeZone类，但他们同样存在上述所有的问题。</li>
</ul>
<p>Java 8 在 <strong>java.time</strong> 包下提供了很多新的 API。以下为两个比较重要的 API：</p>
<ul>
<li><strong>Local(本地)</strong> − 简化了日期时间的处理，没有时区的问题。</li>
<li><strong>Zoned(时区)</strong> − 通过制定的时区处理日期时间。</li>
</ul>
<p>新的java.time包涵盖了所有处理日期，时间，日期&#x2F;时间，时区，时刻（instants），过程（during）与时钟（clock）的操作。</p>
<p><em><strong>Java SE 8在java.time中附带一个新的日期和时间API，为开发人员提供了大大改善的安全性和功能。新的API很好地建模了该领域，并提供了用于对各种开发人员用例进行建模的大量类。</strong></em></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> StringBuffer <span class="title function_">format</span><span class="params">(Date date, StringBuffer toAppendTo,</span></span><br><span class="line"><span class="params">                            FieldDelegate delegate)</span> &#123;</span><br><span class="line">    <span class="comment">// Convert input date to time field list</span></span><br><span class="line">    calendar.setTime(date);</span><br><span class="line"></span><br><span class="line">    <span class="type">boolean</span> <span class="variable">useDateFormatSymbols</span> <span class="operator">=</span> useDateFormatSymbols();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; compiledPattern.length; ) &#123;</span><br><span class="line">        <span class="type">int</span> <span class="variable">tag</span> <span class="operator">=</span> compiledPattern[i] &gt;&gt;&gt; <span class="number">8</span>;</span><br><span class="line">        <span class="type">int</span> <span class="variable">count</span> <span class="operator">=</span> compiledPattern[i++] &amp; <span class="number">0xff</span>;</span><br><span class="line">        <span class="keyword">if</span> (count == <span class="number">255</span>) &#123;</span><br><span class="line">            count = compiledPattern[i++] &lt;&lt; <span class="number">16</span>;</span><br><span class="line">            count |= compiledPattern[i++];</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">switch</span> (tag) &#123;</span><br><span class="line">        <span class="keyword">case</span> TAG_QUOTE_ASCII_CHAR:</span><br><span class="line">            toAppendTo.append((<span class="type">char</span>)count);</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">case</span> TAG_QUOTE_CHARS:</span><br><span class="line">            toAppendTo.append(compiledPattern, i, count);</span><br><span class="line">            i += count;</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">default</span>:</span><br><span class="line">            subFormat(tag, count, delegate, toAppendTo, useDateFormatSymbols);</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> toAppendTo;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>calendar是共享变量，并且这个共享变量没有做线程安全控制。当多个线程同时使用相同的SimpleDateFormat对象【如用static修饰的SimpleDateFormat】调用format方法时，多个线程会同时调用calendar.setTime方法，可能一个线程刚设置好time值另外的一个线程马上把设置的time值给修改了导致返回的格式化时间可能是错误的。</p>
<p>在多并发情况下使用SimpleDateFormat需格外注意SimpleDateFormat除了format是线程不安全以外，parse方法也是线程不安全的。parse方法实际调用alb.establish(calendar).getTime()方法来解析，alb.establish(calendar)方法里主要完成了</p>
<ul>
<li>重置日期对象cal的属性值</li>
<li>使用calb中中属性设置cal</li>
<li>返回设置好的cal对象</li>
</ul>
<p>但是这三步不是原子操作</p>

    </div>

    
    
    

    <footer class="post-footer">
          

<div class="post-copyright">
<ul>
  <li class="post-copyright-author">
      <strong>本文作者： </strong>yorn
  </li>
  <li class="post-copyright-link">
      <strong>本文链接：</strong>
      <a href="http://wang-chen1119.gitee.io/myblog/2022/10/28/java%208%20%E6%96%B0%E7%89%B9%E6%80%A7/" title="java8新特性">http://wang-chen1119.gitee.io/myblog/2022/10/28/java 8 新特性/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>

          <div class="post-tags">
              <a href="/myblog/tags/java%E5%9F%BA%E7%A1%80/" rel="tag"><i class="fa fa-tag"></i> java基础</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/myblog/2022/10/28/java%E9%94%81%E7%9A%84%E5%8D%87%E7%BA%A7%E5%92%8C%E5%AF%B9%E6%AF%94/" rel="prev" title="java锁的升级和对比">
                  <i class="fa fa-chevron-left"></i> java锁的升级和对比
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/myblog/2022/10/28/static%E4%B8%8Efinal%E5%85%B3%E9%94%AE%E5%AD%97/" rel="next" title="static与final关键字">
                  static与final关键字 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">yorn</span>
</div>

    </div>
  </footer>

  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/myblog/js/comments.js"></script><script src="/myblog/js/utils.js"></script><script src="/myblog/js/motion.js"></script><script src="/myblog/js/next-boot.js"></script><script src="/myblog/js/bookmark.js"></script>

  





  





<script src="/myblog/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"log":false,"pluginJsPath":"lib/","pluginModelPath":"assets/","pluginRootPath":"live2dw/","tagMode":false});</script></body>
</html>
